﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Copad.BusinessCard.BLL;
using Copad.BusinessCard.Model;

public partial class CardPermissions : System.Web.UI.Page
{
    GroupBLL groupBLL = new GroupBLL();
    UserBLL userBLL = new UserBLL();
    CardPermissionsBLL permissionsBLL = new CardPermissionsBLL();

    protected List<GroupView> GroupList;
    protected List<UserView> UserList;
    protected long cardID;

    protected void Page_Load(object sender, EventArgs e)
    {
        string ids = Request["id"];

        if (string.IsNullOrEmpty(ids) || !long.TryParse(ids, out cardID))
        {
            Response.Redirect("~/Error.aspx", true);
            return;
        }

        if (!this.IsPostBack)
        {
            LoadData();
        }
    }

    protected void submit_Click(object sender, EventArgs e)
    {
        string groups = Request["Groups"];
        string users = Request["Users"];

        if (string.IsNullOrEmpty(groups))
        {
            groups = "";
        }
        if (string.IsNullOrEmpty(users))
        {
            users = "";
        }
        var groupArray = groups.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        var userArray = users.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        long id;
        List<long> groupID = new List<long>();
        foreach (var item in groupArray)
        {
            if (!long.TryParse(item, out id))
            {
                Response.Redirect("~/Error.aspx?msg=提交了错误的参数！", true);
                return;
            }
            groupID.Add(id);
        }

        List<long> userID = new List<long>();
        foreach (var item in userArray)
        {
            if (!long.TryParse(item, out id))
            {
                Response.Redirect("~/Error.aspx?msg=提交了错误的参数！", true);
                return;
            }
            userID.Add(id);
        }

        try
        {
            Manager.WriteLog(OperationEnum.Update, "用户：" + Manager.CurrentUser.User.Username + " 修改了编号为" + cardID + "的名片的访问权限");
            permissionsBLL.UpdatePermissions(cardID, userID, groupID);
        }
        catch (Exception ex)
        {
            Manager.WriteLog(ex);
            this.Message.Visible = true;
        }
        LoadData();
    }

    private void LoadData()
    {
        GroupList = groupBLL.GetCardPermissions(cardID);
        UserList = userBLL.GetCardPermissions(cardID);
    }
}